import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import oauth
import datastoreWrapper
import logging

class LoginHandler(webapp.RequestHandler):
  def get(self):

    #check for cookie
    if self.request.headers.get('Cookie'):
      self.redirect('/ready')
    #else
    application_key = "6xl9ij2hxqza" 
    application_secret = "EqwoPSV4q8phQtxN"  
    callback_url = "%s/landing" % self.request.host_url
  
    client = oauth.get_oauth_client(oauth.LINKEDIN, application_key, application_secret, callback_url)
    
    if self.request.path == "/":
      auth_url = client.get_authorization_url()
      
      template_values = {
                  #'greetings': greetings,
                  'url': auth_url,
                  #'url_linktext': url_linktext,
              }

      path = os.path.join(os.path.dirname(__file__), 'welcome.html')
      self.response.out.write(template.render(path, template_values))
      #self.response.out.write('<a href="'+auth_url+'">Login</a>')
    
    if self.request.path == "/landing":
      auth_token = self.request.get("oauth_token")
      auth_verifier = self.request.get("oauth_verifier")
      template_values = { 'auth_token' : auth_token,
                          'auth_verifier' : auth_verifier }
      path = os.path.join(os.path.dirname(__file__), 'landing.html')
      return self.response.out.write(template.render(path, template_values))
    
    if self.request.path == "/verify":
      auth_token = self.request.get("oauth_token")
      auth_verifier = self.request.get("oauth_verifier")
      user_info = client.get_user_info(auth_token, auth_verifier=auth_verifier)
      '''
      template_values = { 'first_name' : user_info['name'],
                          'token' : user_info['token'],
                          'secret' : user_info['secret'] }
      path = os.path.join(os.path.dirname(__file__), 'landing.html')
      self.response.out.write(template.render(path, template_values))
      '''      

      connections = client.get_connections(user_info["token"],user_info["secret"])
      logging.error(connections)
      
      memberId = user_info['id']
      name = user_info['name']
      
      membersNeeded = datastoreWrapper.getMembersNeeded(memberId, connections,name)

      
      connections = client.connections_details(user_info["token"],user_info["secret"], membersNeeded)
      logging.error(connections)
      if not len(connections) == 0:
        datastoreWrapper.populateDatastore(connections)
      
      #datastoreWrapper.getPatentsQuery(memberId)
      
      #get member info
      self.response.headers.add_header('Set-Cookie', 'memberId=' + memberId)
      return self.redirect('/ready')

	
